package org.zjt.demo.controller;

import org.zjt.demo.task.WorkTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * DESC 测试动态添加定时任务
 *
 * @author
 * @create 2017-04-17 下午2:27
 **/
@RestController
@Api("动态定时器接口")
public class SchedulerController {

    @Autowired
    SchedulerFactoryBean schedulerFactoryBean;

    @PostMapping("/task")
    @ApiOperation(value = "添加动态定时器")
    public String addTask(@ApiParam(name = "cron",value = "cron表达式",required = true)@RequestParam(name = "cron",required = false) String cron){
        JobDetail jobDetail = JobBuilder.newJob(WorkTask.class).withIdentity("task_id").build();
        jobDetail.getJobDataMap().put("user_name", "zjt");
        jobDetail.getJobDataMap().put("user_age", 24);

        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger_id").withSchedule(scheduleBuilder.withMisfireHandlingInstructionFireAndProceed()).build();

        TriggerKey triggerKey = trigger.getKey();
        try {
            Date e1 = schedulerFactoryBean.getScheduler().scheduleJob(jobDetail, trigger);
            return "设置成功";
        }catch (Exception _e){
            _e.printStackTrace();
        }
        return "设置失败";
    }

    @DeleteMapping("/task")
    @ApiOperation(value = "删除动态定时器")
    public String delTask(@ApiParam(name = "task_id",value = "删除的task_id",required = true)@RequestParam(name = "task_id",required = false) String taskId){
        try {
            schedulerFactoryBean.getScheduler().deleteJob(new JobKey(taskId, "DEFAULT"));
            return "删除成功";
        }catch (Exception _e){
            _e.printStackTrace();
        }
        return "删除失败";
    }



}
